package freedom.ms.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
	 @Autowired
    private AuthenticationManager authenticationManager;
	 /*@Autowired
	    private DataSource dataSource;*/
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    
    @Autowired
	private GenericJackson2JsonSerializationStrategy serializationStrategy;

    @Bean
    RedisTokenStore redisTokenStore(){
    	RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
		redisTokenStore.setSerializationStrategy(serializationStrategy);
		return redisTokenStore;
    }
    
    //token存储数据库
//  @Bean
//  public JdbcTokenStore jdbcTokenStore(){
//      return new JdbcTokenStore(dataSource);
//  }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    	//clients.withClientDetails(clientDetails());
          clients.inMemory()
          .withClient("acme")     //接受的clientId
          .secret("acmesecret")      //默认secret
          .authorizedGrantTypes("authorization_code", "refresh_token")  //授权模式
          .scopes("user_info")      //用来限制客户端的访问范围，如果为空（默认）的话，那么客户端拥有全部的访问范围。
          .autoApprove(true)
          .and()
          .withClient("webapp")
          .authorizedGrantTypes("implicit")
          .and()
          .withClient("android")
          .secret("android")
          .authorizedGrantTypes("password", "authorization_code", "refresh_token")
            ;
    }
    
   /* @Bean
    public ClientDetailsService clientDetails() {
        return new JdbcClientDetailsService(dataSource);
    	
    }*/

    
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    	endpoints.tokenStore(redisTokenStore())
        .userDetailsService(userDetailsService)
        .authenticationManager(authenticationManager);
    		/*endpoints.tokenServices(defaultTokenServices());*/
    }
    /**
     * <p>注意，自定义TokenServices的时候，需要设置@Primary，否则报错，</p>
     * @return
     */
    /*@Primary
    @Bean
    public DefaultTokenServices defaultTokenServices(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(redisTokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setClientDetailsService(clientDetails());
        tokenServices.setAccessTokenValiditySeconds(60*60*12); // token有效期自定义设置，默认12小时
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);//默认30天，这里修改
        return tokenServices;
    }*/

    
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    	security
    	.tokenKeyAccess("permitAll()")
    	.checkTokenAccess("isAuthenticated()")
    	.allowFormAuthenticationForClients();
    }

}
